package jnpf.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.service.VisualdevService;
import jnpf.base.util.DynDicUtil;
import jnpf.base.util.VisualUtils;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.engine.enums.FlowStatusEnum;
import jnpf.engine.service.FlowTaskService;
import jnpf.entity.ZXGL_XiangMuJieXiangEntity;
import jnpf.entity.ZXGL_XiangMuJieXiang_JiaoFuWuEntity;
import jnpf.entity.ZXGL_XiangMuLiXiang_MingXiEntity;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.generater.util.GeneraterSwapUtil;
import jnpf.model.zxgl_xiangmujiexiang.*;
import jnpf.service.ZXGL_XiangMuJieXiangService;
import jnpf.service.ZXGL_XiangMuJieXiang_JiaoFuWuService;
import jnpf.service.ZXGL_XiangMuLiXiang_MingXiService;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * ZXGL_XiangMuJieXiang
 *
 * @版本： V2.0
 * @版权： 河北交投智能交通技术有限责任公司
 * @作者： 数字交投项目组
 * @日期： 2025-03-22
 */
@Slf4j
@RestController
@Api(tags = "ZXGL_XiangMuJieXiang", value = "zxgl")
@RequestMapping("/ZXGL_XiangMuJieXiang")
public class ZXGL_XiangMuJieXiangController {


    @Autowired
    private DynDicUtil dynDicUtil;

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private VisualdevService visualdevService;

    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private ZXGL_XiangMuJieXiangService zXGL_XiangMuJieXiangService;

    @Autowired
    private ZXGL_XiangMuJieXiang_JiaoFuWuService zXGL_XiangMuJieXiang_JiaoFuWuService;

    @Autowired
    private ZXGL_XiangMuLiXiang_MingXiService zxglXiangMuLiXiangMingXiService;

    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 列表
     *
     * @param zXGL_XiangMuJieXiangPagination
     * @return
     */
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZXGL_XiangMuJieXiangPagination zXGL_XiangMuJieXiangPagination) throws IOException {
        List<ZXGL_XiangMuJieXiangEntity> list = zXGL_XiangMuJieXiangService.getList(zXGL_XiangMuJieXiangPagination);
        //处理id字段转名称，若无需转或者为空可删除
        for (ZXGL_XiangMuJieXiangEntity entity : list) {
            entity.setZrr(generaterSwapUtil.userSelectValues(entity.getZrr()));
            entity.setZrrbm(generaterSwapUtil.comSelectValues(entity.getZrrbm()));
            entity.setXmly(dynDicUtil.getDicName(entity.getXmly(), "667353988936504645"));
            entity.setXmlx(dynDicUtil.getDicName(entity.getXmlx(), "667277254828496197"));
        }
        List<ZXGL_XiangMuJieXiangListVO> listVO = JsonUtil.getJsonToList(list, ZXGL_XiangMuJieXiangListVO.class);
        for (ZXGL_XiangMuJieXiangListVO zXGL_XiangMuJieXiangVO : listVO) {
        }


        for (ZXGL_XiangMuJieXiangListVO vo : listVO) {
            FlowTaskEntity flowTaskEntity = flowTaskService.getInfoSubmit(vo.getId());
            if (flowTaskEntity != null) {
                vo.setFlowState(flowTaskEntity.getStatus());
            } else {
                vo.setFlowState(null);
            }
        }
        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zXGL_XiangMuJieXiangPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }


    /**
     * 创建
     *
     * @param zXGL_XiangMuJieXiangCrForm
     * @return
     */
    @PostMapping
    @Transactional
    public ActionResult create(@RequestBody @Valid ZXGL_XiangMuJieXiangCrForm zXGL_XiangMuJieXiangCrForm) throws DataException {
        String visualId = "673059228675503621";
        VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
        String mainId = RandomUtil.uuId();
        UserInfo userInfo = userProvider.get();

        // reggion 赋值部门领导和负责人
        ZXGL_XiangMuLiXiang_MingXiEntity model = zxglXiangMuLiXiangMingXiService.getInfo(zXGL_XiangMuJieXiangCrForm.getXmid());
        zXGL_XiangMuJieXiangCrForm.setDepartmentManagerZzbm(model.getDepartmentManagerZzbm());
        zXGL_XiangMuJieXiangCrForm.setDepartmentHeadleaderZzbm(model.getDepartmentHeadleaderZzbm());
        // endreion

        // region 赋值主责人是否为部门负责人
        if (StrUtil.isNotEmpty(zXGL_XiangMuJieXiangCrForm.getDepartmentManagerZzbm()) && zXGL_XiangMuJieXiangCrForm.getZrr().equals(zXGL_XiangMuJieXiangCrForm.getDepartmentManagerZzbm())) {
            zXGL_XiangMuJieXiangCrForm.setZzrsfbmfzr("669876724938339973"); // 是
        } else {
            zXGL_XiangMuJieXiangCrForm.setZzrsfbmfzr("669876694466721413"); // 否
        }
        // endregion

        ZXGL_XiangMuJieXiangEntity entity = JsonUtil.getJsonToBean(zXGL_XiangMuJieXiangCrForm, ZXGL_XiangMuJieXiangEntity.class);
        entity.setJhjsrq(new Date(zXGL_XiangMuJieXiangCrForm.getJhjsrq()));
        entity.setJhksrq(new Date(zXGL_XiangMuJieXiangCrForm.getJhksrq()));
        entity.setId(mainId);
        entity.setCreatorTime(new Date());
        entity.setZjid(mainId);


        zXGL_XiangMuJieXiangService.save(entity);

        if (zXGL_XiangMuJieXiangCrForm.getZxgl_xiangmujiexiang_jiaofuwuList() != null && zXGL_XiangMuJieXiangCrForm.getZxgl_xiangmujiexiang_jiaofuwuList().size() > 0) {
            List<ZXGL_XiangMuJieXiang_JiaoFuWuEntity> ZXGL_XiangMuJieXiang_JiaoFuWuList = JsonUtil.getJsonToList(zXGL_XiangMuJieXiangCrForm.getZxgl_xiangmujiexiang_jiaofuwuList(), ZXGL_XiangMuJieXiang_JiaoFuWuEntity.class);

            for (ZXGL_XiangMuJieXiang_JiaoFuWuEntity entitys : ZXGL_XiangMuJieXiang_JiaoFuWuList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setMainid(entity.getId());
                zXGL_XiangMuJieXiang_JiaoFuWuService.save(entitys);
            }
        }

        if (FlowStatusEnum.submit.getMessage().equals(zXGL_XiangMuJieXiangCrForm.getStatus())) {
            try {
                VisualUtils.submitFlowTask(visualdevEntity, mainId, zXGL_XiangMuJieXiangCrForm, userInfo, zXGL_XiangMuJieXiangCrForm.getCandidateList());
                FlowTaskEntity flowTaskEntity = flowTaskService.getInfo(mainId);
                if (flowTaskEntity != null) {
                    flowTaskEntity.setTitle(zXGL_XiangMuJieXiangCrForm.getXmmc() + "-项目结项-" + userInfo.getUserName() + "-" + DateUtil.today());
                    flowTaskEntity.setDataTable("zxgl_xiangmujiexiang");
                    flowTaskService.update(flowTaskEntity);
                }
            } catch (WorkFlowException e) {
                e.printStackTrace();
            }
            return ActionResult.success("提交成功，请耐心等待");
        }
        return ActionResult.success("保存成功", mainId);
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ActionResult<ZXGL_XiangMuJieXiangInfoVO> info(@PathVariable("id") String id) {
        ZXGL_XiangMuJieXiangEntity entity = zXGL_XiangMuJieXiangService.getInfo(id);
        ZXGL_XiangMuJieXiangInfoVO vo = JsonUtil.getJsonToBean(entity, ZXGL_XiangMuJieXiangInfoVO.class);

        //子表
        List<ZXGL_XiangMuJieXiang_JiaoFuWuEntity> ZXGL_XiangMuJieXiang_JiaoFuWuList = zXGL_XiangMuJieXiangService.GetZXGL_XiangMuJieXiang_JiaoFuWuList(id);
        for (ZXGL_XiangMuJieXiang_JiaoFuWuEntity zxgl_xiangmujiexiang_jiaofuwuEntity : ZXGL_XiangMuJieXiang_JiaoFuWuList) {

        }
        vo.setZXGL_XiangMuJieXiang_JiaoFuWuList(JsonUtil.getJsonToList(ZXGL_XiangMuJieXiang_JiaoFuWuList, ZXGL_XiangMuJieXiang_JiaoFuWuModel.class));
        //副表
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZXGL_XiangMuJieXiangUpForm zXGL_XiangMuJieXiangUpForm) throws DataException {
        String visualId = "673059228675503621";
        VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
        UserInfo userInfo = userProvider.get();
        ZXGL_XiangMuJieXiangEntity entity = zXGL_XiangMuJieXiangService.getInfo(id);
        if (entity != null) {

            // reggion 赋值部门领导和负责人
            ZXGL_XiangMuLiXiang_MingXiEntity model = zxglXiangMuLiXiangMingXiService.getInfo(zXGL_XiangMuJieXiangUpForm.getXmid());
            zXGL_XiangMuJieXiangUpForm.setDepartmentManagerZzbm(model.getDepartmentManagerZzbm());
            zXGL_XiangMuJieXiangUpForm.setDepartmentHeadleaderZzbm(model.getDepartmentHeadleaderZzbm());
            // endreion

            // region 赋值主责人是否为部门负责人
            if (StrUtil.isNotEmpty(zXGL_XiangMuJieXiangUpForm.getDepartmentManagerZzbm()) && zXGL_XiangMuJieXiangUpForm.getZrr().equals(zXGL_XiangMuJieXiangUpForm.getDepartmentManagerZzbm())) {
                zXGL_XiangMuJieXiangUpForm.setZzrsfbmfzr("669876724938339973"); // 是
            } else {
                zXGL_XiangMuJieXiangUpForm.setZzrsfbmfzr("669876694466721413"); // 否
            }
            // endregion

            ZXGL_XiangMuJieXiangEntity subentity = JsonUtil.getJsonToBean(zXGL_XiangMuJieXiangUpForm, ZXGL_XiangMuJieXiangEntity.class);


            zXGL_XiangMuJieXiangService.update(id, subentity);

            QueryWrapper<ZXGL_XiangMuJieXiang_JiaoFuWuEntity> ZXGL_XiangMuJieXiang_JiaoFuWuqueryWrapper = new QueryWrapper<>();
            ZXGL_XiangMuJieXiang_JiaoFuWuqueryWrapper.lambda().eq(ZXGL_XiangMuJieXiang_JiaoFuWuEntity::getMainid, entity.getId());
            zXGL_XiangMuJieXiang_JiaoFuWuService.remove(ZXGL_XiangMuJieXiang_JiaoFuWuqueryWrapper);

            if (zXGL_XiangMuJieXiangUpForm.getZxgl_xiangmujiexiang_jiaofuwuList() != null && zXGL_XiangMuJieXiangUpForm.getZxgl_xiangmujiexiang_jiaofuwuList().size() > 0) {
                List<ZXGL_XiangMuJieXiang_JiaoFuWuEntity> ZXGL_XiangMuJieXiang_JiaoFuWuList = JsonUtil.getJsonToList(zXGL_XiangMuJieXiangUpForm.getZxgl_xiangmujiexiang_jiaofuwuList(), ZXGL_XiangMuJieXiang_JiaoFuWuEntity.class);
                for (ZXGL_XiangMuJieXiang_JiaoFuWuEntity entitys : ZXGL_XiangMuJieXiang_JiaoFuWuList) {
                    entitys.setId(RandomUtil.uuId());
                    entitys.setMainid(entity.getId());
                    zXGL_XiangMuJieXiang_JiaoFuWuService.save(entitys);
                }
            }

            if (FlowStatusEnum.submit.getMessage().equals(zXGL_XiangMuJieXiangUpForm.getStatus())) {
                try {
                    VisualUtils.submitFlowTask(visualdevEntity, id, subentity, userInfo, zXGL_XiangMuJieXiangUpForm.getCandidateList());
                    FlowTaskEntity flowTaskEntity = flowTaskService.getInfo(id);
                    if (flowTaskEntity != null) {
                        flowTaskEntity.setTitle(zXGL_XiangMuJieXiangUpForm.getXmmc() + "-项目结项-" + userInfo.getUserName() + "-" + DateUtil.today());
                        flowTaskEntity.setDataTable("zxgl_xiangmujiexiang");
                        flowTaskService.update(flowTaskEntity);
                    }
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
                return ActionResult.success("提交成功，请耐心等待");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZXGL_XiangMuJieXiangEntity entity = zXGL_XiangMuJieXiangService.getInfo(id);
        if (entity != null) {
            FlowTaskEntity taskEntity = flowTaskService.getInfoSubmit(id);
            if (taskEntity != null) {
                try {
                    flowTaskService.delete(taskEntity);
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
            }
            zXGL_XiangMuJieXiangService.delete(entity);
            QueryWrapper<ZXGL_XiangMuJieXiang_JiaoFuWuEntity> queryWrapperZXGL_XiangMuJieXiang_JiaoFuWu = new QueryWrapper<>();
            queryWrapperZXGL_XiangMuJieXiang_JiaoFuWu.lambda().eq(ZXGL_XiangMuJieXiang_JiaoFuWuEntity::getMainid, entity.getId());
            zXGL_XiangMuJieXiang_JiaoFuWuService.remove(queryWrapperZXGL_XiangMuJieXiang_JiaoFuWu);

        }
        return ActionResult.success("删除成功");
    }

    @PostMapping("/updateLiXiangMingxi")
    public ActionResult updateLiXiangMingxi(@RequestBody ZXGL_UpdateLiXiangMingxi updateLiXiangMingxi) {
        log.info("更新立项明细表信息==================================================================================");
        log.info(updateLiXiangMingxi.getTaskId());
        ZXGL_XiangMuJieXiangEntity entity = zXGL_XiangMuJieXiangService.getInfo(updateLiXiangMingxi.getTaskId());
        if (entity != null) {
            // 当前流程调用为审批最后一个节点调用，所以更改是否上传知识库状态为2，通过定时器上传附件到知识库
            entity.setSfsczsk(2);
            zXGL_XiangMuJieXiangService.updateById(entity);
            ZXGL_XiangMuLiXiang_MingXiEntity model = zxglXiangMuLiXiangMingXiService.getById(entity.getXmid());
            if (model != null) {
                // 完成情况描述
                model.setWcqksm(entity.getWcqkms());
                // 交付物
                // model.setJxjfw(entity.getJxwj());
                // 实际开始日期和实际完成日期
                model.setSjksrq(entity.getSjksrq());
                model.setSjwcrq(entity.getSjwcrq());
                // 领导评分
                model.setRgpf(entity.getRgpf());
                // 领导评价
                model.setRgpj(entity.getRgpj());
                // ai评分
                model.setAipf(entity.getAipf());
                // ai评价
                model.setAipj(entity.getAipj());

                // 更新进度
                model.setXmjd(new BigDecimal(100));

                model.setZt("667276506048763205");

                boolean update = zxglXiangMuLiXiangMingXiService.updateById(model);
                if (update) {
                    log.info("更新立项明细表信息==========================================================================更新成功");
                    return ActionResult.success("更新成功");
                } else {
                    return ActionResult.fail("更新失败");
                }
            }
        }
        return ActionResult.fail("更新失败，数据不存在");
    }
}
